from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.select import Select
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys
import time


# 基类
class Base():
    # 初始化
    def __init__(self,driver):
        self.driver=driver

    # 封装网址
    def open_url(self,url):
        self.driver.get(url)

    # 封装截屏
    def error_png(self):
        error_png=time.strftime('%Y%m%d-%H%M%S')
        return error_png

    # 封装定位
    def find_element(self,loc):
        try:
            WebDriverWait(self.driver,20,0.5).until(lambda driver:driver.find_element(*loc).is_displayed())
            return self.driver.find_element(*loc)
        except Exception as e:
            self.driver.save_screenshot('./'+self.error_png()+'.png')
            print(e)

    # 封装输入
    def send_keys(self,loc,info):
        self.find_element(loc).send_keys(info)
    # 封装点击
    def click(self,loc):
        self.find_element(loc).click()
    # 封装滚动条
    def scrollTo(self,x):
        self.driver.execute_script(f'window scrollTO(0,{x})')
    # 封装弹框
    def alert(self):
        self.driver.switch_to.alert()
    # 封装iframe
    def frame(self,loc):
        self.driver.switch_to.frame(self.driver.find_element(loc))
    # 封装切换页面
    def window(self):
        self.driver.switch_to.window(self.driver.window_handles[-1])
    # 封装鼠标事件
    def double(self,loc):
        ActionChains(self.driver).double_click(loc).perform()

    # 封装键盘事件
    def keys(self,loc,x):
        self.driver.find_element(loc).send_keys(Keys.CONTROL,x)
    # 封装浏览器事件
    def arlt(self):
        self.arlt()

    # 封装下拉框
    def select_by_value(self,loc,value):
        Select(self.driver.find_element(loc)).select_by_value(value)
    def select_by_index(self,loc,index):
        Select(self.driver.find_element(loc)).select_by_index(index)
    def select_by_text(self,loc,text):
        Select(self.driver.find_element(loc)).select_by_visible_text(text)